<template>
    <div>
        <el-button type="primary" @click="handleVisible(true)">特殊商品积分设置</el-button>
        <el-dialog
            class="special_template_dialog"
            title="特殊商品设置"
            v-model="visible"
            width="80%"
            @close="handleVisible(false)">
            <div class="special_template_dialog_header">
                <el-form ref="formRef" :model="form" label-width="auto">
                    <el-row justify="space-between">
                        <el-col :span="8">
                            <el-form-item label="商品名称" prop="goodsName">
                                <el-input v-model="form.goodsName" clearable placeholder="请输入商品名称"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="padding-left: 24px">
                            <el-form-item label="来源店铺" prop="shopId">
                                <el-select
                                    v-model="form.shopId"
                                    filterable
                                    reserve-keyword
                                    clearable
                                    placeholder="请选择">
                                    <el-option
                                        v-for="item in shopList"
                                        :key="item.shopId"
                                        :label="item.shopName"
                                        :value="item.shopId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="padding-left: 24px; text-align: right">
                            <el-button @click="resetHandler">清空</el-button>
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <div class="center-operation">
                <!-- <el-button type="primary">新增商品</el-button> -->
                <BatchDialog :disabled="disabled" @handle-confirm="searchHandler" :good-ids="goodIds"></BatchDialog>
                <AddGood :disabled="disabled" @handle-confirm="searchHandler"></AddGood>
            </div>
            <el-table :data="tableList" @selection-change="handleSelectionChange" ref="multipleTableRef" height="250">
                <el-table-column type="selection" width="55" />
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <div class="custom-goods-name" v-if="prop === 'goodsName'">
                            <el-image
                                style="width: 40px; height: 40px; min-width: 40px"
                                :src="row?.materialSrc?.[0]?.materialSrc"
                                fit="fill"></el-image>
                            <el-tooltip effect="dark" :content="row.goodsName" placement="top">
                                <span class="custom-goods-name-span">{{ row.goodsName }}</span>
                            </el-tooltip>
                        </div>
                        <el-input-number
                            v-if="prop === 'givePoints'"
                            v-model="row.givePoints"
                            :disabled="disabled"
                            class="custom-number-small"
                            :min="1"
                            :max="99999999"
                            :precision="0"
                            :controls="false" />
                        <el-button v-if="prop === 'operations'" size="small" @click="handleRemove(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
            <template #footer v-if="!disabled">
                <div style="flex: auto">
                    <el-button plain @click="handleVisible(false)">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { cloneDeep } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import AddGood from './addGood.vue';
import BatchDialog from './batchDialog.vue';
import request from '@/request';
import Pagination from '@/components/Pagination.vue';
import { getShopListHook } from '@/hooks';

const props = defineProps({
    disabled: {
        type: Boolean,
        default: false
    }
});

const form = reactive({
    shopId: 0,
    goodsName: null,
    page: 1,
    perPage: 10
});
const formRef = ref();
const formClone = cloneDeep(form);
const totalCount = ref(0);
let tableList = reactive([]);
// const tableColumns = reactive([
//     { label: '商品名称', prop: 'goodsName', minWidth: '150' },
//     { label: '价格（元）', prop: 'price' },
//     { label: '来源店铺', prop: 'shopInfoText', width: '100' },
//     { label: '每消费1元赠送积分', prop: 'givePoints' }
// ]);
const tableColumns = computed(() => {
    const columns = [
        { label: '商品名称', prop: 'goodsName', minWidth: '150' },
        { label: '价格（元）', prop: 'price' },
        { label: '来源店铺', prop: 'shopInfoText', showOverflowTooltip: true },
        { label: '每消费1元赠送积分', prop: 'givePoints' }
    ];
    if (!props.disabled) {
        columns.push({ label: '操作', prop: 'operations', width: '100' });
    }
    return columns;
});
let visible = ref(false);
const multipleTableRef = ref();
const multipleSelection = ref([]);
let shopList = reactive([]);
let goodIds = reactive([]);

const handleVisible = (isVisible = false) => {
    if (!isVisible) {
        multipleTableRef.value?.clearSelection();
        Object.assign(form, cloneDeep(formClone));
        queryCouponListHandler();
    }
    visible.value = isVisible;
};
const handleConfirm = async () => {
    if (tableList.find(item => item.givePoints === null)) {
        ElMessage({
            type: 'error',
            message: '积分不能为空'
        });
        return;
    }
    if (tableList.find(item => item.givePoints === 0)) {
        ElMessage({
            type: 'error',
            message: '积分不能小于1'
        });
        return;
    }
    await request('pointsGoodsSave', {
        goodsList: tableList?.map(item => {
            return {
                goodId: item.goodsId,
                givePoints: item.givePoints * 100
            };
        })
    });
    handleVisible(false);
    searchHandler();
};
const handleSelectionChange = val => {
    goodIds.length = 0;
    Object.assign(
        goodIds,
        val?.map(item => item.goodsId)
    );
};

const handleRemove = async row => {
    await request('pointsRemoveConfig', {
        shopId: row.shopId,
        goodsList: [row?.materialSrc?.[0]?.goodsId]
    });
    ElMessage({
        type: 'success',
        message: '删除成功'
    });
    queryCouponListHandler();
};

const handleBatch = () => {
    if (multipleSelection.value.length < 1) {
        ElMessage({
            type: 'error',
            message: '请先选择商品'
        });
        return;
    }
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    queryCouponListHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    queryCouponListHandler();
};
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */

const getshopList = async () => {
    const { data } = await getShopListHook();
    shopList.length = 0;
    const list = data.list;
    list.unshift({ shopName: '全部店铺', shopId: 0 });
    Object.assign(shopList, list);
};

const queryCouponListHandler = async () => {
    const { data } = await request('pointsGoodsList', form);
    tableList.length = 0;
    Object.assign(
        tableList,
        (data.list || []).map(item => {
            const min = Math.min(...(item?.skuInfo?.map(item => item.skuPrice) || []));
            const max = Math.max(...(item?.skuInfo?.map(item => item.skuPrice) || []));
            if (!item?.skuInfo || !item?.skuInfo?.length) {
                item.price = '-';
            } else if (min === max) {
                item.price = `￥${min / 100}`;
            } else {
                item.price = `￥${min / 100}~￥${max / 100}`;
            }
            item.shopInfoText = item?.shopInfo?.shopName;
            item.givePoints = item.givePoints / 100;
            return item;
        })
    );
    totalCount.value = data.totalCount;
};

onMounted(() => {
    getshopList();
    searchHandler();
});
</script>

<style lang="scss">
.special_template_dialog {
    max-width: 1000px;
    min-width: 900px;
    .el-table {
        border-bottom: 1px solid #eaeaea !important;
    }
}
</style>
<style lang="scss" scoped>
.special_template_dialog {
    .custom-number-small {
        width: 100px;
    }
    &_header {
        width: 100%;
        .el-form > div {
            flex-wrap: nowrap;
        }
    }

    .custom-goods-name {
        display: inline-flex;
        align-items: center;
        width: 100%;
        &-span {
            margin-left: 4px;
            display: -webkit-box;
            max-width: calc(100% - 45px);
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }
    }
    .center-operation {
        margin-top: 20px;
        padding: 20px 0;
        display: flex;
        border-top: 1px solid #eaeaea;
        justify-content: space-between;
        :deep {
            .is-text {
                padding: 0;
            }
        }
    }
}
</style>
